﻿/*
 * 2012-12 zyy
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SRF.UI
{
    /// <summary>
    /// 保存页面状态
    /// </summary>
    public class ViewState : System.Web.Mvc.ActionFilterAttribute
    {
        public override void OnResultExecuting(System.Web.Mvc.ResultExecutingContext filterContext)
        {
            System.Web.HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
            //获取页面信息
            for (int i = 0; i < request.Form.Count; i++)
            {
                if (filterContext.Controller.ViewData.ContainsKey(request.Form.AllKeys[i]) == false)
                {
                    filterContext.Controller.ViewData.Add(request.Form.AllKeys[i], request.Form[i]);
                }
            }
            base.OnResultExecuting(filterContext);
        }

        public override void OnResultExecuted(System.Web.Mvc.ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);

            StringBuilder doPostBackStript = new StringBuilder();
            doPostBackStript.AppendLine("<script type='text/javascript'>");
            doPostBackStript.AppendLine("function __doPostBack() {");
            doPostBackStript.AppendLine("if (typeof ($) == 'function' && document.forms.length > 0) {");
            doPostBackStript.AppendLine("var formId, selector;");
            doPostBackStript.AppendLine("if (arguments.length == 1) {");
            doPostBackStript.AppendLine("selector = arguments[0];");
            doPostBackStript.AppendLine("}");
            doPostBackStript.AppendLine("else if (arguments.length > 2) {");
            doPostBackStript.AppendLine("formId = arguments[0];");
            doPostBackStript.AppendLine("selector = arguments[1];");
            doPostBackStript.AppendLine("}");
            doPostBackStript.AppendLine("else");
            doPostBackStript.AppendLine("return;");
            doPostBackStript.AppendLine("var form = formId == undefined ? document.forms[0] : document.getElementById(formId);");
            doPostBackStript.AppendLine("if (form != null) {");
            doPostBackStript.AppendLine("$(selector).filter('[href]').click(function () {");
            doPostBackStript.AppendLine("form.action = $(this).attr('href');");
            doPostBackStript.AppendLine("form.reset();");
            doPostBackStript.AppendLine("form.submit();");
            doPostBackStript.AppendLine("return false;");
            doPostBackStript.AppendLine("})");
            doPostBackStript.AppendLine("}");
            doPostBackStript.AppendLine("}");
            doPostBackStript.AppendLine("}");
            doPostBackStript.AppendLine("</script>");

            filterContext.RequestContext.HttpContext.Response.Write(doPostBackStript.ToString());
        }
    }
}